<template>
  <div class="profile">
    <el-card class="card">
      <template #header>
        <div class="header">
          <h2 class="title">个人资料</h2>
          <el-button
            v-if="profileMode === Mode.Detail"
            type="primary"
            plain
            @click="profileMode = Mode.Edit"
            >编辑</el-button
          >
          <el-button v-else type="primary" plain @click="handleReturn">返回</el-button>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="form"
        :rules="profileMode === Mode.Edit ? rules : emptyRules"
        label-position="right"
        label-width="150px"
        label-suffix="："
        :validate-on-rule-change="false"
      >
        <el-form-item label="账号审核状态">
          <el-tag v-if="form.state === '0'" type="warning">未认证</el-tag>
          <el-tag v-if="form.state === '1'">审核中</el-tag>
          <el-tag v-if="form.state === '2'" type="success">已通过</el-tag>
          <el-tag v-if="form.state === '3'" type="danger">未通过</el-tag>
        </el-form-item>
        <el-form-item label="头像">
          <el-avatar v-if="form.avatar" :size="40" :src="form.avatar" />
          <img v-else style="width: 40px" src="@/assets/images/default-avatar.png" />
          <el-upload
            class="avatar-uploader m-l-10"
            v-if="profileMode === Mode.Edit"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.nickname"
            placeholder="请输入昵称"
          />
          <span v-else>{{ form.nickname }}</span>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.email"
            placeholder="请输入邮箱"
          />
          <span v-else>{{ form.email }}</span>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.phone"
            placeholder="请输入手机号"
          />
          <span v-else>{{ form.phone }}</span>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-if="profileMode === Mode.Edit" v-model="form.gender">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
          <span v-else>{{ form.gender === '0' ? '男' : '女' }}</span>
        </el-form-item>
        <el-form-item label="单位性质" prop="unitNature">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.unitNature"
            placeholder="请输入单位性质"
          />
          <span v-else>{{ form.unitNature }}</span>
        </el-form-item>
        <el-form-item label="关联组织" prop="associatedOrganizations">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.associatedOrganizations"
            placeholder="请输入关联组织"
          />
          <span v-else>{{ form.associatedOrganizations }}</span>
        </el-form-item>
        <el-form-item class="industry" label="行业领域" prop="industrySector">
          <el-select
            v-if="profileMode === Mode.Edit"
            v-model="form.industrySector"
            multiple
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="option in industrySectorList"
              :key="option.label"
              :label="option.label"
              :value="option.label"
              placeholder="请选择行业领域"
            ></el-option>
          </el-select>
          <el-tag v-else class="m-r-10" v-for="(name, index) in form.industrySector" :key="index">
            {{ name }}
          </el-tag>
        </el-form-item>
        <el-form-item label="所在单位" prop="company">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="form.company"
            placeholder="请输入所在单位"
          />
          <span v-else>{{ form.company }}</span>
        </el-form-item>
        <!-- 如果角色类型是讲师，才展示 -->
        <div v-if="roleKeys.includes(Role.Lecturer)" class="lecturer">
          <el-form-item label="职称" prop="professionalTitle">
            <el-input
              v-if="profileMode === Mode.Edit"
              v-model="form.professionalTitle"
              placeholder="请输入职称"
            />
            <span v-else>{{ form.professionalTitle }}</span>
          </el-form-item>
        </div>
        <!-- 如果角色类型是技术专家，才展示 -->
        <div v-if="roleKeys.includes(Role.Technician)" class="lecturer">
          <el-form-item label="技术栈" prop="technologyStack">
            <div v-if="profileMode === Mode.Edit">
              <div class="flex">
                <el-input
                  style="width: 200px"
                  v-model="form.technologyStack"
                  placeholder="请输入技术栈名称"
                ></el-input>
                <el-button type="primary" @click="addTech">添加</el-button>
              </div>
              <div class="m-t-10">
                <el-tag
                  v-for="(tech, index) in techStack"
                  :key="index"
                  closable
                  @close="removeTech(index)"
                  class="m-r-10"
                >
                  {{ tech }}
                </el-tag>
              </div>
            </div>
            <el-tag v-else class="m-r-10" v-for="(tech, index) in techStack" :key="index">
              {{ tech }}
            </el-tag>
          </el-form-item>
        </div>

        <!-- 企业资料展示 -->

        <el-form-item
          v-if="!roleKeys.includes(Role.Enterprise)"
          label="简介"
          prop="briefIntroduction"
        >

          <div v-if="profileMode === Mode.Edit" style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="form.briefIntroduction"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
          <div
            v-else
            style="padding: 20px; border: 1px solid #ccc; width: 100%"
            class="wang-editor-html"
            v-html="form.briefIntroduction"
          ></div>
        </el-form-item>
        <el-form-item
          v-if="
            roleKeys.includes(Role.Enterprise) && profileMode === Mode.Edit && !user.enterpriseId
          "
          label="是否填写企业信息"
        >
          <el-radio-group v-model="isEditEnterpriseInfo" class="ml-4">
            <el-radio :label="true" size="large">是</el-radio>
            <el-radio :label="false" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 如果角色类型是企业人员，才展示 -->
      <!-- <h3>请选择是加入已有企业还是新增企业信息</h3>
      <el-radio-group v-model="radio1" class="ml-4">
      <el-radio label="1" size="large">加入已有企业</el-radio>
      <el-radio label="2" size="large">新增企业信息</el-radio>
    </el-radio-group>
      <el-select
        v-model="selectedEnterprise"
        filterable
        remote
        reserve-keyword
        placeholder="Please enter a keyword"
        :remote-method="remoteMethod"
      >
        <el-option
          v-for="item in enterpeiseList"
          :key="item.value"
          :label="item.name"
          :value="item.id"
        />
      </el-select> -->
      <el-form
        v-if="roleKeys.includes(Role.Enterprise) && isEditEnterpriseInfo"
        ref="enterpriseFormRef"
        :model="enterpriseForm"
        :rules="profileMode === Mode.Edit ? enterpriseRules : emptyRules"
        label-position="right"
        label-width="150px"
        label-suffix="："
        :validate-on-rule-change="false"
      >
        <el-form-item label="企业审核状态">
          <el-tag v-if="enterpriseForm.auditState === 0" type="warning">未认证</el-tag>
          <el-tag v-if="enterpriseForm.auditState === 2">审核中</el-tag>
          <el-tag v-if="enterpriseForm.auditState === 1" type="success">已通过</el-tag>
          <el-tag v-if="enterpriseForm.auditState === -1" type="danger">未通过</el-tag>
        </el-form-item>
        <el-form-item v-if="enterpriseForm.auditState === -1" label="审核失败原因">
          <span>{{ enterpriseForm.auditRemark }}</span>
        </el-form-item>
        <el-form-item label="社会信用代码" prop="code">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.code"
            placeholder="请输入社会信用代码"
          />
          <span v-else>{{ enterpriseForm.code }}</span>
        </el-form-item>
        <el-form-item label="企业名称" prop="name">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.name"
            placeholder="请输入企业名称"
          />
          <span v-else>{{ enterpriseForm.name }}</span>
        </el-form-item>
        <el-form-item label="企业类型" prop="type">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.type"
            placeholder="请输入企业类型"
          />
          <span v-else>{{ enterpriseForm.type }}</span>
        </el-form-item>
        <el-form-item label="法定代表人" prop="representative">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.representative"
            placeholder="请输入法定代表人"
          />
          <span v-else>{{ enterpriseForm.representative }}</span>
        </el-form-item>
        <el-form-item label="企业营业执照" prop="businessLicense">
          <el-image
            style="width: 100px; height: 100px"
            :src="enterpriseForm.businessLicense"
            :zoom-rate="1.2"
            :preview-src-list="[enterpriseForm.businessLicense]"
            :initial-index="4"
            fit="cover"
          />
          <el-upload
            class="businessLicense-uploader m-l-10"
            v-if="profileMode === Mode.Edit"
            :on-remove="handleBusinessLicenseRemove"
            :on-change="handleBusinessLicenseChange"
            :show-file-list="false"
            :before-upload="beforeBusinessLicenseUpload"
            :auto-upload="false"
          >
            <img v-if="businessLicenseImageUrl" :src="businessLicenseImageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="注册资本（万元）" prop="registeredCapital">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.registeredCapital"
            placeholder="请输入注册资本"
          />
          <span v-else>{{ enterpriseForm.registeredCapital }}</span>
        </el-form-item>
        <el-form-item label="注册地址" prop="registeredAddress">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.registeredAddress"
            placeholder="请输入注册地址"
          />
          <span v-else>{{ enterpriseForm.registeredAddress }}</span>
        </el-form-item>
        <el-form-item label="公司联系电话" prop="telephone">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.telephone"
            placeholder="请输入公司联系电话"
          />
          <span v-else>{{ enterpriseForm.telephone }}</span>
        </el-form-item>
        <el-form-item label="公司邮箱" prop="mail">
          <el-input
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.mail"
            placeholder="请输入公司邮箱"
          />
          <span v-else>{{ enterpriseForm.mail }}</span>
        </el-form-item>
        <el-form-item label="公司成立时间" prop="establishmentTime">
          <el-date-picker
            class="date-picker"
            v-if="profileMode === Mode.Edit"
            v-model="enterpriseForm.establishmentTime"
            type="date"
            placeholder="请选择公司成立时间"
            :clearable="false"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
          <span v-else>{{ enterpriseForm.establishmentTime }}</span>
        </el-form-item>
        <el-form-item
          v-if="roleKeys.includes(Role.Enterprise)"
          label="公司简介"
          prop="briefIntroduction"
        >
          <div v-if="profileMode === Mode.Edit" style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="enterpriseForm.briefIntroduction"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
          <div
            v-else
            style="padding: 20px; border: 1px solid #ccc; width: 100%"
            class="wang-editor-html"
            v-html="enterpriseForm.briefIntroduction"
          ></div>
        </el-form-item>
      </el-form>
      <div style="text-align: right" v-if="profileMode === Mode.Edit">
        <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef } from 'vue';
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadFile,
  type UploadFiles,
  type UploadProps,
  type UploadRawFile,
} from 'element-plus';
import { editUserInfo, getUserInfo } from '@/api/system';
import { useUserStore } from '@/store/user';
import { uploadFile } from '@/api/file';
import { Plus } from '@element-plus/icons-vue';
import type { IToolbarConfig } from '@wangeditor/editor';
import { useEditorConfig } from '@/hooks/useEditorConfig';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { Role } from '@/types/type';
import { industrySectorList } from '@/data/industrySector';
import { enterpriseDetail, enterpriseList, enterprisePost, enterprisePut } from '@/api/enterpeise';
import { reqFeedback } from '@/utils/reqFeedback';

onMounted(() => {
  getCurUserInfo();
});

const isEditEnterpriseInfo = ref(true);

const originalForm = ref({} as any);
const originalEnterpriseForm = ref({} as any);
// 添加原始技术栈数据的引用
const originalTechStack = ref<string[]>([]);

// // 选择企业
// const enterpeiseList = ref<any[]>([]);
// const selectedEnterprise = ref('');
// const remoteMethod = (keyword: string) => {
//   if (keyword) {
//     enterpriseList({ auditState: 1, name: keyword }).then((res: any) => {
//       enterpeiseList.value = res.data.records.filter((item: any) => {
//         return item.name.includes(keyword);
//       });
//     });
//   } else {
//     enterpeiseList.value = [];
//   }
// };

// 获取用户信息
const user = ref({} as any);
const roleKeys = ref([] as any[]);
const userStore = useUserStore();
function getCurUserInfo() {
  getUserInfo().then((res: any) => {
    console.log('asd', res);

    if (res.code === 200) {
      user.value = res.user!;
      userStore.userInfo.userMsg = res.user;
      roleKeys.value = res.user.roles?.map((item: any) => item.roleKey);
      techStack.value = res.user.technologyStack ?? [];
      // 备份原始技术栈数据
      originalTechStack.value = [...techStack.value];
      // 为表单赋值
      form.avatar = res.user.avatar;
      form.nickname = res.user.nickName;
      form.email = res.user.email;
      form.phone = res.user.phonenumber;
      form.gender = res.user.sex;
      form.unitNature = res.user.unitNature;
      form.associatedOrganizations = res.user.associatedOrganizations;
      form.industrySector = res.user.industrySector;
      form.company = res.user.company;
      form.professionalTitle = res.user.professionalTitle;
      form.technologyStack = ''; // 这里是输入框中的数据，置空即可
      form.briefIntroduction = res.user.briefIntroduction ?? '';
      form.state = res.user.state;
      // 备份个人资料原始数据
      originalForm.value = { ...form };
      originalForm.value.industrySector = [...form.industrySector]; // 数组需要深拷贝
      // 如果用户角色是企业人员，且已完善企业信息，则获取企业信息
      const eId = user.value.enterpriseId;
      if (roleKeys.value.includes(Role.Enterprise) && eId) {

        enterpriseDetail(eId).then((res: any) => {
          console.log('dsfd', res);
          if (res.code === 200) {

            enterpriseForm.code = res.data.code;
            enterpriseForm.name = res.data.name;
            enterpriseForm.type = res.data.type;
            enterpriseForm.representative = res.data.representative;
            enterpriseForm.businessLicense = res.data.businessLicense;
            enterpriseForm.registeredCapital = res.data.registeredCapital;
            enterpriseForm.registeredAddress = res.data.registeredAddress;
            enterpriseForm.telephone = res.data.telephone;
            enterpriseForm.mail = res.data.mail;
            enterpriseForm.establishmentTime = res.data.establishmentTime;
            enterpriseForm.briefIntroduction = res.data.briefIntroduction;
            enterpriseForm.otherMaterials = res.data.otherMaterials;
            enterpriseForm.id = res.data.id;
            enterpriseForm.auditState = res.data.auditState;
            enterpriseForm.auditRemark = res.data.auditRemark;

            // 备份企业表单原始数据（重要：这里需要备份）
            originalEnterpriseForm.value = { ...enterpriseForm };
          }
        });
      }
      // else if (roleKeys.value.includes(Role.Enterprise) && !eId) {
      //   // 如果用户角色是企业人员，且用户未填写企业信息，则用户可选择加入企业
      //   enterpriseList({ auditState: 1 }).then((res) => {
      //     console.log(res);
      //   });
      // }
    }
  });
}

// 修改返回按钮的处理逻辑
const handleReturn = () => {
  profileMode.value = Mode.Detail;
  // 恢复原始数据
  Object.assign(form, originalForm.value);
  // 数组属性需要特殊处理
  form.industrySector = [...originalForm.value.industrySector];

  // 恢复技术栈原始数据
  techStack.value = [...originalTechStack.value];
  // 清空输入框
  form.technologyStack = '';

  // 如果是企业用户，恢复企业信息原始数据
  if (roleKeys.value.includes(Role.Enterprise)) {
    // 如果有原始企业数据，则恢复；否则重置为企业表单初始状态
    if (originalEnterpriseForm.value && Object.keys(originalEnterpriseForm.value).length > 0) {
      Object.assign(enterpriseForm, originalEnterpriseForm.value);
    } else {
      // 重置为企业表单初始状态
      Object.assign(enterpriseForm, {
        id: undefined,
        code: '',
        name: '',
        type: '',
        representative: '',
        businessLicense: '',
        registeredCapital: '',
        registeredAddress: '',
        telephone: '',
        mail: '',
        establishmentTime: '',
        otherMaterials: '',
        briefIntroduction: '',
        auditState: undefined,
        auditRemark: '',
      });
    }
  }

  // 清除表单验证状态
  nextTick(() => {
    formRef.value?.clearValidate();
    enterpriseFormRef.value?.clearValidate();
  });
};

// 新增技术栈
const techStack = ref<string[]>([]);
const addTech = () => {
  if (form.technologyStack) {
    techStack.value.push(form.technologyStack);
    form.technologyStack = '';
  }
  nextTick(() => {
    formRef.value?.validateField('technologyStack');
  });
};
const removeTech = (index: number) => {
  techStack.value.splice(index, 1);
};

// 富文本编辑器
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const mode = 'default';
const toolbarConfig: Partial<IToolbarConfig> = {};
const { editorConfig } = useEditorConfig();
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 头像上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
};
let imageFile: UploadRawFile | null;
const imageUrl = ref<string>();
// 头像删除
function handleRemove(file: UploadFile, fileList: UploadFiles) {
  imageFile = null;
  imageUrl.value = '';
}
// 头像修改
function handleChange(file: UploadFile, fileList: UploadFiles) {
  if (file.raw) {
    imageFile = file.raw;
    imageUrl.value = URL.createObjectURL(file.raw);
  }
}

enum Mode {
  Detail = 'Detail',
  Edit = 'Edit',
}

// 编辑个人资料
const profileMode = ref<Mode>(Mode.Detail);

// 用户基本信息表单
const form = reactive({
  avatar: '',
  nickname: '',
  email: '',
  phone: '',
  gender: '',
  briefIntroduction: '', // 简介
  unitNature: '', // 单位性质
  associatedOrganizations: '', // 关联组织
  industrySector: [], // 行业领域
  company: '', // 所在单位
  // 讲师额外信息
  professionalTitle: '', //职称
  // 技术专家额外信息
  technologyStack: '', // 技术栈
  state: '', // 认证状态
});

// 企业表单
const enterpriseForm = reactive({
  id: undefined as any,
  code: '',
  name: '',
  type: '',
  representative: '',
  businessLicense: '',
  registeredCapital: '',
  registeredAddress: '',
  telephone: '',
  mail: '',
  establishmentTime: '',
  otherMaterials: '',
  briefIntroduction: '',
  auditState: undefined,
  auditRemark: '',
});

// 个人信息的表单校验
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  briefIntroduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  industrySector: [{ required: true, message: '请选择行业领域', trigger: 'change' }],
  company: [{ required: true, message: '请输入所在单位', trigger: 'blur' }],
  technologyStack: [{ required: true, validator: validateTechStack, trigger: 'blur' }],
});
function validateTechStack(rule: any, value: any, callback: any) {
  if (!techStack.value.length) {
    callback(new Error('技术栈不能为空'));
  }
  callback();
}
// 企业信息的表单校验
const enterpriseFormRef = ref<FormInstance>();
const enterpriseRules = reactive<FormRules>({
  code: [{ required: true, message: '请输入社会信用代码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  type: [{ required: true, message: '请输入企业类型', trigger: 'blur' }],
  representative: [{ required: true, message: '请输入法定代表人', trigger: 'blur' }],
  businessLicense: [{ required: true, message: '请上传企业营业执照', trigger: 'blur' }],
  registeredCapital: [
    { required: true, message: '请输入注册资本', trigger: 'blur' },
    { pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入正确的金额格式，最多10位整数，最多2位小数', trigger: 'blur' }
  ],
  registeredAddress: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  telephone: [
    { required: true, message: '请输入公司联系电话', trigger: 'blur' },
    { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
  ],
  mail: [
    { required: true, message: '请输入公司邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  establishmentTime: [{ required: true, message: '请选择公司成立时间', trigger: 'change' }],
  briefIntroduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
});



const emptyRules = reactive<FormRules>({});

// 营业执照文件
let businessLicenseFile: UploadRawFile | null = null;
const businessLicenseImageUrl = ref('');

// 企业营业执照
const beforeBusinessLicenseUpload = (file: File) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('只能上传 jpg/png 格式的图片');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
  }
  return isImage && isLt2M;
};
// 删除营业执照
const handleBusinessLicenseRemove = (file: UploadFile) => {
  businessLicenseFile = null;
  businessLicenseImageUrl.value = '';
  // 清空表单字段
  enterpriseForm.businessLicense = '';
};
// 修改营业执照
const handleBusinessLicenseChange = (file: UploadFile) => {
  if (file.raw) {

    businessLicenseFile = file.raw;
    businessLicenseImageUrl.value = URL.createObjectURL(file.raw);
    // 立即更新表单字段，用于表单验证
    enterpriseForm.businessLicense = 'temp'; // 设置临时值通过验证
  }
};

const submitting = ref(false);

// 修改 submitForm 方法，确保企业表单验证完成后才提交
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const eId = user.value.enterpriseId;

      // 处理头像上传
      if (imageFile) {
        const formData = new FormData();
        formData.append('file', imageFile);
        const res: any = await uploadFile(formData);
        if (res.code === 200) {
          user.value.avatar = res.data.url;
        } else {
          ElMessage.error(res.msg);
          return;
        }
      }

      // 如果是企业用户且选择填写企业信息，则需要验证企业表单
      if (roleKeys.value.includes(Role.Enterprise) && isEditEnterpriseInfo.value) {
        enterpriseFormRef.value?.validate(async (enterpriseValid) => {
          if (enterpriseValid) {
            await submitAllForms();
          }
        });
      } else {
        // 非企业用户或企业用户选择不填写企业信息，直接提交
        await submitAllForms();
      }
    }
  });
};

// 将提交逻辑提取到单独的函数中
const submitAllForms = async () => {
  transferRequestData();

  // 处理营业执照上传
  if (businessLicenseFile) {
    const formData = new FormData();
    formData.append('file', businessLicenseFile);
    const res: any = await uploadFile(formData);

    if (res.code === 200) {
      enterpriseForm.businessLicense = res.data.url;
    } else {
      ElMessage.error(res.msg);
      return;
    }
  }

  // 提交用户基本信息
  const res: any = await editUserInfo(user.value);
  if (res.code === 200) {
    const eId = user.value.enterpriseId;

    // 如果是企业用户且需要处理企业信息
    if (roleKeys.value.includes(Role.Enterprise) && isEditEnterpriseInfo.value) {
      // 提交企业信息
      let enterpriseRes: any;
      if (eId) {
        // 编辑企业信息
        enterpriseRes = await enterprisePut(enterpriseForm);
      } else {
        // 新增企业信息
        enterpriseRes = await enterprisePost(enterpriseForm);
      }

      reqFeedback(enterpriseRes, '修改成功');
    } else {
      ElMessage({
        message: '修改成功',
        type: 'success',
      });
    }

    profileMode.value = Mode.Detail;
    resetForm();
    getCurUserInfo();
  }
};
// 重置表单
function resetForm() {
  form.avatar = '';
  form.nickname = '';
  form.email = '';
  form.phone = '';
  form.gender = '';
  form.briefIntroduction = '';
  form.unitNature = '';
  form.associatedOrganizations = '';
  form.industrySector = [];
  form.company = '';
  form.professionalTitle = '';
  form.technologyStack = '';
}

// 将表单转换成接口需要的数据
function transferRequestData() {
  user.value.nickName = form.nickname;
  user.value.email = form.email;
  user.value.phonenumber = form.phone;
  user.value.sex = form.gender;
  user.value.briefIntroduction = form.briefIntroduction;
  user.value.unitNature = form.unitNature;
  user.value.associatedOrganizations = form.associatedOrganizations;
  user.value.industrySector = form.industrySector;
  user.value.company = form.company;
  user.value.professionalTitle = form.professionalTitle;
  user.value.technologyStack = techStack;
}
</script>

<style scoped lang="scss">
.profile {
  padding: 20px;
  .card {
    width: 1000px;
    padding: 30px;
    margin: 0 auto;
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .industry :deep(.el-select) {
      width: 40% !important;
    }
  }
}
/* 富文本编辑器样式增强 */
:deep(.w-e-text-container b),
:deep(.w-e-text-container strong),
:deep(.wang-editor-html b),
:deep(.wang-editor-html strong) {
  font-weight: bold;
}

// 图片上传
.avatar-uploader .avatar,
.businessLicense-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.avatar-uploader :deep(.el-upload),
.businessLicense-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover),
.businessLicense-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
</style>
